<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告框 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品 -->
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="{
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children',
            }"
            @change="parentCateChanged"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 操作参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数的按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- tag与button切换输入 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 上面为输入的文本框下面为添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="id"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态参数表格 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- tag与button切换输入 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 上面为输入的文本框下面为添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="id"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加属性、参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 添加参数的表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改属性、参数对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 修改的表单 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //存储商品列表数据
      cateList: [],
      //存储被选中的值双向绑定
      selectedCateKeys: [],
      //当前默认活动的页
      activeName: 'many',
      //存储动态和静态的数据
      manyTableData: [],
      onlyTableData: [],
      //对话框
      addDialogVisible: false,
      //存储添加数据表单数据
      addForm: {
        attr_name: '',
      },
      //添加表单验证规则
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: '不可为空！',
            trigger: 'blur',
          },
        ],
      },
      //修改功能数据存放区
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        attr_name: [
          {
            required: true,
            message: '不可为空！',
            trigger: 'blur',
          },
        ],
      },
      //默认隐藏输入框显示点击按钮
      inputVisible: false,
      //双向绑定的值
      inputValue: '',
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //获取所有的商品分类列表
    async getCateList() {
      const { data: response } = await this.$http.get('categories');
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      this.cateList = response.data;
    },
    //级联选择器选项发生变化触发
    parentCateChanged() {
      this.getParamsData();
    },
    //当选项卡发生变化执行
    handleTabClick() {
      this.getParamsData();
    },
    //获取参数的列表数据
    async getParamsData() {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }
      //当选择了三级分类则发起请求
      const { data: response } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      response.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
        //控制文本输入框的显示与隐藏
        item.inputVisible = false;
        //文本输入框的值
        item.inputValue = '';
      });
      if (this.activeName === 'many') this.manyTableData = response.data;
      else this.onlyTableData = response.data;
    },
    //监听添加对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //当确认添加了执行
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: response } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (response.meta.status !== 201)
          return this.$message({
            message: response.meta.msg,
            type: 'error',
            center: true,
          });
        this.$message({
          message: response.meta.msg,
          type: 'success',
          center: true,
        });
        this.addDialogVisible = false;
        this.getParamsData();
      });
    },
    //点击了修改按钮展示对话框
    async showEditDialog(attr_id) {
      const { data: response } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: { attr_sel: this.activeName },
        }
      );
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      this.editForm = response.data;
      this.editDialogVisible = true;
    },
    //关闭对话框
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: response } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (response.meta.status !== 200)
          return this.$message({
            message: response.meta.msg,
            type: 'error',
            center: true,
          });
        this.$message({
          message: response.meta.msg,
          type: 'success',
          center: true,
        });
        this.getParamsData();
        this.editDialogVisible = false;
      });
    },
    //当对话框关闭执行重置表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //删除参数
    async removeParams(attr_id) {
      const confirmResult = await this.$confirm('确认删除该参数?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err);
      if (confirmResult !== 'confirm') return;
      const { data: response } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      );
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      this.getParamsData();
    },
    //来回切换生成tag的文本框失去焦点或按下enter键都会触发
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = '';
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = '';
      row.inputVisible = false;
      //上述操作只能保存到页面中下面发起请求保存到数据库中
      this.saveAttrVals(row);
    },
    showInput(row) {
      row.inputVisible = true;
      //让文本框自动聚焦(因为渲染了很多分不清是要哪个聚焦所以精确查找)
      this.$nextTick((_) => {
        //页面重新渲染后执行
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //监听tag标签点击了x号执行用index区分当前是谁点击了x
    async handleClose(index, row) {
      const confirmResult = await this.$confirm('确认永久删除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err);
      if (confirmResult !== 'confirm') return;
      row.attr_vals.splice(index, 1);
      this.saveAttrVals(row);
    },
    //将对attr_vals的操作发送请求保存到数据库
    async saveAttrVals(row) {
      const { data: response } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      );
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
    },
  },
  computed: {
    //如果按钮返回true则禁用
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) return true;
      return false;
    },
    //当前选中的三级分类的id
    cateId() {
      if (this.selectedCateKeys.length === 3) return this.selectedCateKeys[2];
      return null;
    },
    //动态计算标题的文本
    titleText() {
      if (this.activeName === 'many') return '动态参数';
      return '静态属性';
    },
  },
};
</script>

<style scoped>
.cat_opt {
  margin: 15px 0;
}

.el-tag {
  margin: 8px;
}

.input-new-tag {
  width: 120px;
}
</style>